/**
 * @module:  ant mobile listview二次封装
 * @author: Liang Huang
 * @date: 2019-12-28 14:27:26
 */

import React, { useState, CSSProperties, useImperativeHandle, useRef, useEffect } from 'react';
import { ListView, ActivityIndicator, PullToRefresh } from 'antd-mobile';
import _ from 'lodash';
import './index.less';

const dataSource = new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2 });

interface IListViewProps {
  data: any[];
  onPullDown?: () => Promise<any>;
  onPullUp?: () => Promise<any>;
  styleHeight: number;
  hasMore?: boolean;
  renderHeader?:
    | (() => React.ReactElement<
        any,
        | string
        | ((
            props: any
          ) => React.ReactElement<any, string | any | (new (props: any) => React.Component<any, any, any>)> | null)
        | (new (props: any) => React.Component<any, any, any>)
      >)
    | undefined;
  renderFooter?:
    | (() => React.ReactElement<
        any,
        | string
        | ((
            props: any
          ) => React.ReactElement<any, string | any | (new (props: any) => React.Component<any, any, any>)> | null)
        | (new (props: any) => React.Component<any, any, any>)
      >)
    | undefined;
  renderRow: (
    rowData: any,
    sectionID: React.ReactText,
    rowID: React.ReactText,
    highlightRow?: boolean | undefined
  ) => React.ReactElement<
    any,
    | string
    | ((props: any) => React.ReactElement<any, string | (new (props: any) => React.Component<any>)> | null)
    | (new (props: any) => React.Component<any>)
  >;
  style?: CSSProperties;
  useBodyScroll?: boolean;
  [propName: string]: any;
  scrollHandler?: Function;
}

const ListViewWithPp = (props: IListViewProps, ref: any) => {
  const {
    data,
    style,
    styleHeight,
    onPullDown,
    onPullUp,
    className,
    renderRow,
    renderFooter,
    hasMore,
    scrollHandler
  } = props;
  const [loading, setLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const listViewRef = useRef<any>(null);
  let styleParams = {};
  if (style) {
    styleParams = { ...style, height: styleHeight };
  } else {
    styleParams = { height: styleHeight };
  }

  useImperativeHandle(ref, () => listViewRef.current, [listViewRef]);

  // if(useBodyScroll) {
  //   styleParams = {};
  // }
  function onRefresh() {
    if (onPullDown) {
      setRefreshing(true);
      onPullDown().finally(() => setRefreshing(false));
    }
    // getFetch().then(() => setRefreshing(false))
  }

  function onEndReached() {
    console.log('reached');
    if (loading || !data || !data.length || !hasMore) return;
    if (onPullUp) {
      setLoading(true);
      onPullUp().finally(() => {
        console.log('do here');
        setLoading(false);
      });
    }
  }

  const realProps = _.omit(props, ['ref']);
  return (
    <ListView
      ref={listViewRef}
      {...realProps}
      style={styleParams}
      className={className || ''}
      contentContainerStyle={{ position: 'relative' }}
      dataSource={dataSource.cloneWithRows(data)}
      // ref={listRef}
      // @ts-ignore
      pullToRefresh={<PullToRefresh refreshing={refreshing} onRefresh={onRefresh} />}
      onEndReached={onEndReached}
      onScroll={e => scrollHandler && scrollHandler(e)}
      renderFooter={
        renderFooter
          ? renderFooter
          : () => {
              if (loading || hasMore)
                return (
                  <div className="load-more" style={{ textAlign: 'center' }}>
                    {loading ? <ActivityIndicator key="loading" text="加载中" /> : ''}
                  </div>
                );
              return <div style={{ textAlign: 'center' }}>已经到底了</div>;
            }
      }
      renderRow={renderRow}
    />
  );
};

// forwardRef不能与observer一起用
export default React.forwardRef(ListViewWithPp);